package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/7/22 22:25
 * https://leetcode.cn/problems/reverse-nodes-in-k-group/
 */
public class Title25 {

    class ListNode {
        int val;

        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        ListNode newHead = new ListNode(-1);
        newHead.next = head;
        //记录每次翻转后的第一个节点的前驱节点
        ListNode pre = newHead;
        //记录每次翻转前的第一个节点
        ListNode temp = head;
        //遍历节点
        ListNode cur = head;
        int count = 1;
        while (cur != null) {
            cur = cur.next;
            count++;
            if (cur == null) {
                return newHead.next;
            }
            //翻转前k个
            if (count == k) {
                pre.next = cur;
                cur = cur.next;
                pre = cur;
                ListNode start = temp;
                while (temp != cur) {
                    ListNode t = temp.next;
                    temp.next = pre;
                    pre = temp;
                    temp = t;
                }
                pre = start;
                count = 1;
            }
        }
        return newHead.next;
    }

    public static void main(String[] args) {
        int n = 123456789;
        StringBuffer sb = new StringBuffer(String.valueOf(n));
        for (int i = sb.length() - 3; i > 0; i -= 3){
            sb.insert(i, '.');
        }
        System.out.println(sb.toString());
    }
}
